package com.winhxd.b2c.customer.service.impl;

import com.winhxd.b2c.common.cache.Cache;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.constant.CacheName;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.customer.condition.ShoppingMallRuleCondition;
import com.winhxd.b2c.common.domain.customer.model.CustomerShoppingMallRule;
import com.winhxd.b2c.common.domain.customer.vo.ShoppingMallRuleVO;
import com.winhxd.b2c.common.domain.system.user.model.SysUser;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.feign.system.UserServiceClient;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.customer.dao.CustomerShoppingMallRuleMapper;
import com.winhxd.b2c.customer.service.ShoppingMallRuleService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author: lishaoping
 * @Date: 2019年1月8日17:02:39
 * @Description:
 */
@Service
public class ShoppingMallRuleServiceImpl implements ShoppingMallRuleService {
    private static final Logger logger = LoggerFactory.getLogger(ShoppingMallRuleServiceImpl.class);

    //初始化参数 0
    private static final int INITIALIZE_PARAM_0 = 0;

    //初始化参数 1.00
    private static final BigDecimal INITIALIZE_PARAM_1 = new BigDecimal("1.00");

    //分隔符
    private static final String SEPARATOR = ",";

  @Autowired
    private CustomerShoppingMallRuleMapper customerShoppingMallRuleMapper;

    @Autowired
    private UserServiceClient userServiceClient;

    @Resource
    private Cache redisClusterCache;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveShoppingMallRule(ShoppingMallRuleCondition condition) {

        //参数校验
        validateCondition(condition);
        CustomerShoppingMallRule customerShoppingMallRule = new CustomerShoppingMallRule();
        ResponseResult<SysUser> result = userServiceClient.getSysUserById(condition.getSysUserId());
        SysUser user = result.getData();
        CustomerShoppingMallRule rule = customerShoppingMallRuleMapper.selectShoppingMallRule();
        if (null == rule) {
            //新增操作
            BeanUtils.copyProperties(condition,customerShoppingMallRule);
            customerShoppingMallRule.setOrderCloseRule(condition.getOrderCloseRuleDays()*24*60+condition.getOrderCloseRuleHours()*60+condition.getOrderCloseRuleMinutes());
            customerShoppingMallRule.setCreated(new Date());
            customerShoppingMallRule.setCreatedBy(condition.getSysUserId());
            customerShoppingMallRule.setCreatedName(user.getUsername());
            customerShoppingMallRuleMapper.insertSelective(customerShoppingMallRule);
        }else {
            //更新操作
            BeanUtils.copyProperties(condition,customerShoppingMallRule);
            customerShoppingMallRule.setOrderCloseRule(condition.getOrderCloseRuleDays()*24*60+condition.getOrderCloseRuleHours()*60+condition.getOrderCloseRuleMinutes());
            customerShoppingMallRule.setUpdated(new Date());
            customerShoppingMallRule.setUpdatedBy(condition.getSysUserId());
            customerShoppingMallRule.setUpdatedName(user.getUsername());
            customerShoppingMallRuleMapper.updateShoppingMallRule(customerShoppingMallRule);
        }
        redisClusterCache.set(CacheName.SHOPPING_MALL_RULE,JsonUtil.toJSONString(customerShoppingMallRule));
        redisClusterCache.expire(CacheName.SHOPPING_MALL_RULE, 90 * 24 * 60 * 60);
        return true;
    }

    @Override
    public ShoppingMallRuleVO findShoppingMallRule(ShoppingMallRuleCondition condition) {
        ShoppingMallRuleVO vo = new ShoppingMallRuleVO();
        CustomerShoppingMallRule rule = new CustomerShoppingMallRule();
        //判断必填参数
        if (null == condition) {
            throw new BusinessException(BusinessCode.CODE_1007);
        }
        if (null == condition.getSysUserId()) {
            throw new BusinessException(BusinessCode.CODE_1007);
        }
        if(redisClusterCache.exists(CacheName.SHOPPING_MALL_RULE)){
            String json=redisClusterCache.get(CacheName.SHOPPING_MALL_RULE);
            if(StringUtils.isNotEmpty(json)) {
                rule = JsonUtil.parseJSONObject(json,CustomerShoppingMallRule.class);
            }
        } else {
            rule = customerShoppingMallRuleMapper.selectShoppingMallRule();
            redisClusterCache.set(CacheName.SHOPPING_MALL_RULE,JsonUtil.toJSONString(rule));
            redisClusterCache.expire(CacheName.SHOPPING_MALL_RULE, 90 * 24 * 60 * 60);
        }
        BeanUtils.copyProperties(rule,vo);
        int time = rule.getOrderCloseRule();
        int hours = (int) Math.floor(time / 60);
        int minute = time % 60;
        int days = (int) Math.floor(hours / 24);
        hours = hours % 24;
        vo.setOrderCloseRuleDays(days);
        vo.setOrderCloseRuleHours(hours);
        vo.setOrderCloseRuleMinutes(minute);
        if (null != rule.getOrderMobile()) {
            String[] orderMobiles = rule.getOrderMobile().split(SEPARATOR);
            List<String> orderMobileList = Arrays.asList(orderMobiles);
            vo.setOrderMobileList(orderMobileList);
        }
        if (null != rule.getAftersaleMobile()) {
            String[] aftersaleMobiles = rule.getAftersaleMobile().split(SEPARATOR);
            List<String> aftersaleMobileList = Arrays.asList(aftersaleMobiles);
            vo.setAftersaleMobileList(aftersaleMobileList);
        }
        return vo;
    }

    private void validateCondition(ShoppingMallRuleCondition condition) {
        //判断必填参数
        if (null == condition) {
            throw new BusinessException(BusinessCode.CODE_1007);
        }
        if (null == condition.getName()) {
            throw new BusinessException(BusinessCode.CODE_200021);
        }
        if (null == condition.getSysUserId()) {
            throw new BusinessException(BusinessCode.CODE_1007);
        }
        if (null == condition.getOrderCloseRuleDays()) {
            condition.setOrderCloseRuleDays(INITIALIZE_PARAM_0);
        }
        if (null == condition.getOrderCloseRuleHours()) {
            condition.setOrderCloseRuleHours(INITIALIZE_PARAM_0);
        }
        if (null == condition.getOrderCloseRuleMinutes()) {
            condition.setOrderCloseRuleMinutes(INITIALIZE_PARAM_0);
        }
        if (null == condition.getOrderReceiveRule()) {
            throw new BusinessException(BusinessCode.CODE_200022);
        }
        if (null == condition.getReflectRule()) {
            condition.setReflectRule(INITIALIZE_PARAM_1);
        }
        if (null == condition.getExchangeTime()) {
            throw new BusinessException(BusinessCode.CODE_1007);
        }
    }
}
